#include "server.h"
#include "ui_server.h"

server::server(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::server)
{
    ui->setupUi(this);
    setWindowTitle("服务器");
    myserver =new QTcpServer(this);
    myserver->listen(QHostAddress::Any,9999);
    connect(myserver,&QTcpServer::newConnection,this,&server::newconnect);
}

server::~server()
{
    delete ui;
}


void server::newconnect()
{
    mysocket = myserver->nextPendingConnection();
    connect(mysocket,&QTcpSocket::readyRead,this,&server::readsocket);
    connect(mysocket,&QTcpSocket::disconnected,this,[=]()
    {
        ui->message_textBrowser->append("断开连接");
        mysocket->close();
    });
}

void server::readsocket()
{
    QByteArray data=mysocket->readAll();
    ui->message_textBrowser->append("客户端："+data);
}

void server::on_send_pushButton_clicked()
{
    QString msg=ui->send_textBrowser->toPlainText();
    if(msg=="")
    {
        return;
    }
    mysocket->write(msg.toUtf8());
    ui->message_textBrowser->append("服务端："+msg);
    ui->send_textBrowser->clear();
}
